#include <stdlib.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/ioctl.h>
#include <errno.h>
#include <string.h>
#include <linux/watchdog.h>

#define WDOG_DEV        "/dev/watchgod"

int main(int argc, char *argv[])
{
    struct watchdog_info info;
    int timeout;
    int time;
    int fd;
    int op;
    
    if (argc != 2) {
        fprintf(stderr, "usage: %s <timeout> \n", argv[0]);
        exit(EXIT_FAILURE);
    }

    // 打开看门狗
    fd = open(WDOG_DEV, O_RDWR);
    if (fd < 0) {
        fprintf(stderr, "open error:%s:%s\n", WDOG_DEV, strerror(errno));
        exit(EXIT_FAILURE);
    }


    // 关闭定时器
    op = WDIOS_DISABLECARD;
    if ( (ioctl(fd, WDIOC_SETOPTIONS, op)) < 0 ) {
        fprintf(stderr, "ioctl error, WDIOC_SETOPTIONS: %s\n", strerror(errno));
        close(fd);
        exit(EXIT_FAILURE);
    }

    timeout = atoi(argv[1]);
    if (timeout < 1) {
        timeout= 1;
    }
    
    // 设置超时时间
    if ((ioctl(fd, WDIOC_SETTIMEOUT, &timeout)) < 0 ) {
        fprintf(stderr, "ioctl error, WDIOC_SETTIMOUT: %s \n", strerror(errno));
        close(fd);
        exit(EXIT_FAILURE);
    }

    // 开启看门狗定时器
    op = WDIOS_ENABLECARD;
    if ( (ioctl(fd, WDIOC_SETOPTIONS, op)) < 0 ) {
        fprintf(stderr, "ioctl error, WDIOC_SETOPTIONS: %s\n", strerror(errno));
        close(fd);
        exit(EXIT_FAILURE);
    }

    // 喂狗
    time = (timeout * 1000 - 100) * 1000;

    while (1) {
        usleep(time);
        ioctl(fd, WDIOC_KEEPALIVE, NULL);
    }

    return 0;
}
